<template>
  <el-card shadow="always"  body-style="{ padding: '20px' }"> 
<template #header>
  <el-button 
  type="primary"
   size="default" 
   :icon="Plus"
    @click="addTrademark"
        >添加</el-button
      >
</template>
<!-- 中间表格 -->
 <el-table :style="{marginBottom: '30px'}" :data="tabelData" border stripe>
    <el-table-column label="序号" align="center" type="index" width="80" />
      <el-table-column prop="tmName" label="品牌名称"></el-table-column>
      <el-table-column prop="logoUrl"  label="品牌LOGO">
      <!-- 图片接收真实值下面是插槽 row取的是真实的值-->
      <template #default="{ row }">
          <img height="60" :src="row.logoUrl" alt="" />
        </template>
      </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
        <el-button 
        type="warning" 
        size="small" 
        :icon="Edit"
         @click="updateTrademark(row)"
          >修改</el-button
        >
        <el-button
         type="danger"
          size="small"
           :icon="Delete" 
           @click=""
          >删除</el-button
        >
      </template>
      </el-table-column>
    </el-table>

<!-- 分页 -->
    <el-pagination
    v-model:page-size="limit"
      v-model:current-page="page"
      :page-sizes="[3, 5, 7, 9]"
      :pager-count="5"
      layout="prev, pager, next,sizes"
      :total="total"
    />
  </el-card>
<!-- 对话框dialog -->
<el-dialog
    v-model="dialogFormVisible"
    :title="newTrademark.id ? '修改品牌' : '添加品牌'"
  >
    <el-form label-width="100px">
      <el-form-item label="品牌名称">
        <el-input autocomplete="off" v-model="newTrademark.tmName" />
      </el-form-item>
      <el-form-item label="品牌LOGO">
        <!-- ${baseUrl}遍历环境变量有可能上线环境进行改变后面是直接用接口不用再去请求 -->
        <el-upload
          class="avatar-uploader"
          :action="`${baseUrl}/admin/product/upload`"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="newTrademark.logoUrl"
            :src="newTrademark.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateOrAddTrademark">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Trademark",
});
</script>

<script setup lang="ts">
import {ref,toRefs,onMounted,watch} from "vue"
import { Plus, Edit, Delete, UploadFilled } from "@element-plus/icons-vue";
import {
  requestTrademarkList,
  requestUpdateTrademark ,
  requestAddTrademark,
} from "@/api/trademark";
import type {
   reqTrademarkReturnRecordsType,
   reqAddTradeParamsType,
  reqTrademarkReturnItemType,
  } from "@/api/trademark";
//上传的
import { ElMessage, type UploadProps } from "element-plus";
//1.table的逻辑
//table数据
const tabelData = ref<reqTrademarkReturnRecordsType>([]);
  // {
  //   //这个属性值是从后端对应的名字
  //   id: 1,
  //   tmName: "小米",
  //   logoUrl: "/static/default.jpg",
 //   以上是假数据
  // },
  
//2.页码逻辑
//页码的数据和类型
interface pageDateType {
  page: number;
  limit: number;
  total: number;
}
const pageDate = ref<pageDateType>({
  page: 1,
  limit: 3,
  total: 100,
});
//解构出页码的属性
const { page, limit, total } = toRefs(pageDate.value);

//监听页码的改变 然后重新发送请求
watch([page, limit], () => {
  getTrademarkList();
});

//3.获取品牌列表
//封装获取品牌列表的功能函数
const getTrademarkList = async () => {
  const result = await requestTrademarkList({
    page: page.value,
    limit: limit.value,
  });

  //把请求回来的值设置给响应数据
  tabelData.value = result.records;
  total.value = result.total;
};
//初始化
onMounted(() => {
  //调用获取品牌列表的功能函数
  getTrademarkList();
});

//4.弹窗逻辑
//控制弹窗显示隐藏的数据
const dialogFormVisible = ref(false);
//因为上面逻辑不能写 所以着写让后直接给变量赋值 根据生产开发环境不同
//newTrademark拿到数据 
const baseUrl = import.meta.env.VITE_API_URL;
const newTrademark = ref<reqTrademarkReturnItemType>({
  //logoUrl 品牌LOGO   tmName 品牌名字上面定义的有
logoUrl:'',
tmName:'',
//不能设置固定数据 填个id 因为是空所以 可以添加个 因为和你写的v-model双向绑定有个bug所以设置
id:0,
});
//上传逻辑   前三行是element  cv 后面是拿去数据
const handleAvatarSuccess: UploadProps["onSuccess"] = (
response,
UploadFille
) => {
  newTrademark.value.logoUrl = response.data;
  console.log(response);
};
//图片限制
const beforeAvatarUpload :  UploadProps["beforeUpload"]=(rawFile)=> { 
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format");
    return false;
  } else if (rawFile.size / 1024 / 1024 >2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};
//5.添加逻辑
const addTrademark = ()=>{
  dialogFormVisible.value = true;
  newTrademark.value={
    logoUrl:'',
    tmName:'',
    id:0,
  };
};

//6.修改逻辑
const updateTrademark = async (row: reqTrademarkReturnItemType)=>{
  dialogFormVisible.value = true;
  //获取当前的数据然后进行回填数据
  //拿到当前的数据浅拷贝赋值给表单的数据newTrademark(为了数据不会互相影响)
  newTrademark.value = {...row};
};

//7.新增和修改提交
  const updateOrAddTrademark = async () => {
    dialogFormVisible.value = false;
    try {
      if (newTrademark.value.id) { 
        //修改提交 
        await requestUpdateTrademark(newTrademark.value);
        ElMessage.success('修改成功')
      }else{
        //新增提交
        await requestAddTrademark(newTrademark.value)
        ElMessage.success('新增成功');
        page.value = 1;
      }
    } catch (e) {
    ElMessage(newTrademark.value.id ? "修改错误" : "新增错误");
  }
  getTrademarkList();
};



/*
//最完成的解构ref属性的带类型的写法
  const {
    page,
    limit,
    total,
  }: { page: Ref<number>; limit: Ref<number>; total: Ref<number> } =
    toRefs<pageDateType>(pageDate.value);

  //对象解构如何限制类型(一般不会限制,因为都能推断出来)
  const o = { a: 1, b: 2 };
  const { a, b }: { a: number; b: number } = o;
  console.log(a, b);
*/
</script>

<style scoped>
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  </style>
  
  <style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
  </style>
  